<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="咨询方式" prop="type" style="width: 200px;">
        <el-select v-model="queryParams.type" placeholder="请选择咨询方式" clearable>
          <el-option
              v-for="dict in consultation_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>



    <el-table v-loading="loading" :data="appointmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="预约ID" align="center" prop="appointmentId"/>
      <el-table-column label="预约开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="咨询方式" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="consultation_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="预约状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="appointment_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="用户备注" align="center" prop="notes"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <!-- 修改表格操作按钮 -->
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="View"
              @click="handleView(scope.row)">
            查看详情
          </el-button>
          <el-button
              link
              type="warning"
              icon="Edit"
              @click="handleProcess(scope.row)">
            处 理
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 咨询预约对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="appointmentRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <!-- 左侧用户信息列 -->
          <el-col :span="10">
            <el-card class="consultant-card">
              <div class="consultant-info">
                <!-- 新增标题 -->
                <h3 class="user-info-title">用户信息</h3>

                <div class="avatar-section">
                  <image-preview
                      :src="form.userAvatar"
                      class="profile-avatar"
                      :preview-src-list="[form.userAvatar]"
                  />
                  <!-- 添加姓名前缀 -->
                  <div class="username-wrapper">
                    <span class="name-prefix">用户姓名：</span>
                    <h3>{{ form.username }}</h3>
                  </div>
                </div>

                <!-- 调整联系信息样式 -->
                <div class="contact-info">
                  <div class="info-item">
                    <el-icon>
                      <User/>
                    </el-icon>
                    <span>性别：</span>
                    <el-tag type="primary">{{ sexMapper(form.userSex) }}</el-tag>
                  </div>
                  <div class="info-item">
                    <el-icon>
                      <Phone/>
                    </el-icon>
                    <span>电话：{{ form.userPhonenumber || '暂无' }}</span>
                  </div>
                  <div class="info-item">
                    <el-icon>
                      <Message/>
                    </el-icon>
                    <span>邮箱：{{ form.useEmail || '暂无' }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>

          <!-- 右侧预约信息 -->
          <el-col :span="14">
            <el-card class="appointment-card">
              <div class="card-content-wrapper">
                <div class="form-section">
                  <!-- 禁用所有表单项 -->
                  <el-form-item label="开始时间" prop="startTime">
                    <el-input :value="parseTime(form.startTime, '{y}-{m}-{d} {h}:{i}')"
                              :disabled="isViewMode || isProcessMode"/>
                  </el-form-item>
                  <el-form-item label="结束时间" prop="endTime"> <!-- 修正prop属性 -->
                    <el-input :value="parseTime(form.endTime, '{y}-{m}-{d} {h}:{i}')"
                              :disabled="isViewMode || isProcessMode"/>
                  </el-form-item>
                  <el-form-item label="咨询方式" prop="type">
                    <el-radio-group v-model="form.type">
                      <el-radio-button
                          v-for="dict in consultation_type"
                          :key="dict.value"
                          :label="dict.value"
                          :disabled="isViewMode || isProcessMode"
                      >{{ dict.label }}
                      </el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="预约地址" v-if="form.type === '1'">
                    <el-input
                        v-model="form.address"
                        type="textarea"
                        :rows="4"
                        resize="none"
                        :disabled="isViewMode || isProcessMode"
                    />
                  </el-form-item>

                  <el-form-item label="用户备注" prop="notes">
                    <el-input
                        v-model="form.notes"
                        type="textarea"
                        :rows="4"
                        placeholder="无备注信息"
                        resize="none"
                        :disabled="isViewMode || isProcessMode"
                    />
                  </el-form-item>

                  <el-divider v-if="isProcessMode">状态处理</el-divider>

                  <div class="status-section">
                    <!-- 处理模式时显示审批选项 -->
                    <el-form-item
                        label="处理结果"
                        prop="status"
                        v-if="isProcessMode"
                        class="approval-section">
                      <el-radio-group
                          v-model="form.status"
                          :disabled="!isProcessMode">
                        <el-radio-button
                            v-for="dict in is_agree"
                            :key="dict.value"
                            :label="dict.value"
                            :value="dict.value"
                        >{{ dict.label }}
                        </el-radio-button>
                      </el-radio-group>
                    </el-form-item>

                    <!-- 拒绝原因输入 -->
                    <el-form-item
                        label="拒绝原因"
                        prop="reason"
                        v-if="form.status === '1' && isProcessMode">
                      <el-input
                          v-model="form.reason"
                          type="textarea"
                          :rows="3"
                          placeholder="请输入拒绝原因"
                          resize="none"
                          :disabled="!isProcessMode"
                      />
                    </el-form-item>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-form>
      <template #footer v-if="isProcessMode">
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Appointment">
import {
  listAppointment,
  getAppointment,
  handleApprove
} from "@/api/appointment/appointment";
import {parseTime} from "@/utils/ruoyi.js";
import {getCurrentInstance, onMounted, computed} from "vue";
import {format} from 'date-fns';

const {proxy} = getCurrentInstance();
const {
  consultation_type,
  appointment_status,
  sys_user_sex,
  is_agree
} = proxy.useDict('sys_user_sex', 'consultation_type', 'appointment_status', 'is_agree');

const appointmentList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeScheduledTime = ref([]);
const isViewMode = computed(() => title.value === '查看详情');
const isProcessMode = computed(() => title.value === '处理预约');

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    scheduledTime: null,
    type: null,
    status: null,
    notes: null,
  },
  rules: {
    scheduledTime: [
      {required: true, message: "预约时间不能为空", trigger: "blur"}
    ],
    type: [
      {required: true, message: "咨询方式不能为空", trigger: "change"}
    ],
    notes: [
      {required: true, message: "用户备注不能为空", trigger: "blur"}
    ],
    status: [
      {required: true, message: "处理结果不能为空", trigger: "change"}
    ],
    reason: [
      {required: true, message: "拒绝原因不能为空", trigger: "blur"}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询咨询预约列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeScheduledTime && '' != daterangeScheduledTime) {
    queryParams.value.params["beginScheduledTime"] = daterangeScheduledTime.value[0];
    queryParams.value.params["endScheduledTime"] = daterangeScheduledTime.value[1];
  }
  listAppointment(queryParams.value).then(response => {
    appointmentList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

//  性别字典映射
function sexMapper(value) {
  for (let i = 0; i < sys_user_sex.value.length; i++) {
    if (sys_user_sex.value[i].value === value) {
      return sys_user_sex.value[i].label;
    }
  }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    appointmentId: null,
    userId: null,
    counselorId: null,
    type: null,
    status: null,
    reason: null,
    notes: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null
  };
  proxy.resetForm("appointmentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeScheduledTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.appointmentId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加咨询预约";
}

/** 查看详情按钮操作 */
function handleView(row) {
  reset();
  const _appointmentId = row.appointmentId || ids.value
  getAppointment(_appointmentId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "查看详情";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["appointmentRef"].validate(valid => {
    if (valid) {
      if (form.value.startTime) {
        form.value.startTime = format(new Date(form.value.startTime), "yyyy-MM-dd HH:mm:ss");
      }
      if (form.value.endTime) {
        form.value.endTime = format(new Date(form.value.endTime), "yyyy-MM-dd HH:mm:ss");
      }
      let data = {
        counselorId: form.value.counselorId,
        userId: form.value.userId,
        status: form.value.status,
      }
      if (form.value.status === '1') {
        data.reason = form.value.reason
      }
      // 前端状态转换
      if (form.value.status === '1') {
        data.status = '4'
      } else if (form.value.status === '0') {
        data.status = '1'
      }
      handleApprove(data).then(response => {
        if (response.code === 200) {
          open.value = false;
          getList();
        }
      })
    }
  });
}

/** 审批操作 */
function handleProcess(row) {
  reset();
  getAppointment(row.appointmentId).then(response => {
    form.value = {
      ...response.data,
      appointmentResult: null, // 重置审批状态
      reason: null // 重置拒绝原因
    };
    open.value = true;
    title.value = "处理预约";
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('appointment/appointment/export', {
    ...queryParams.value
  }, `appointment_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
})
</script>

<style scoped>
.form-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between; /* 内容均匀分布 */
}

.appointment-card {
  height: 100%; /* 确保卡片撑满父容器高度 */
}

.card-content-wrapper {
  display: flex;
  flex-direction: column;
  justify-content: center; /* 垂直居中 */
  min-height: 400px; /* 根据实际内容调整最小高度 */
  height: 100%;
}

.status-section {
  margin-top: 20px;
}

.approval-section {
  margin-bottom: 25px;
}

/* 处理模式下突出显示审批区域 */
.approval-section :deep(.el-radio-button) {
  margin: 0 10px;
}

/* 拒绝原因输入框样式 */
.reason-input {
  margin-top: 15px;
}

.user-info-title {
  text-align: center;
  margin: 0 0 20px 0;
  color: #333;
  font-size: 16px;
}

.username-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin: 15px 0;
}

.name-prefix {
  color: #666;
  font-size: 14px;
}

.contact-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 18px;
  padding: 10px 0;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
  justify-content: center;
  padding: 8px 0;
}
</style>
